<?php
namespace Admin\Model;

use Zend\Db\TableGateway\TableGateway;

class BaseTable
{
	protected $tableGateway;
	protected $primaryKey = 'id';
	
	public function __construct(TableGateway $tableGateway) {
		$this->tableGateway = $tableGateway;
	}
	
	function fetchAll()
	{
		$resultSet = $this->tableGateway->select();
		return $resultSet;
	}
	
	public function get($id)
	{
		$id = (int) $id;
		$rowset = $this->tableGateway->select(array($this->primaryKey	=> $id));
		$row = $rowset->current();
		if(!$row)
			throw new \Exception("Could not find row $id");
		return $row;
	}
	public function save($object)
	{
		$properties = get_object_vars($object);
		
		foreach($properties as $property => $value)
		{
			$data[$property] = $object->{$property};
		}
		
		$id = (int)$object->{$this->primaryKey};
		
		if($id==0){
			$this->tableGateway->insert($data);
		}else{
			if($this->get($id)){
				$this->tableGateway->update($data,array($this->primaryKey=>$id));
			}else{
				throw new \Exception("Form id does not exist");
			}
		}
	}
	
	public function delete($id)
	{
		$this->tableGateway->delete(array($this->primaryKey => $id));
	}
}